package com.acmedcare.framework.exchange.center.core.application;

import com.acmedcare.framework.exchange.center.core.PluginMetadata;
import com.acmedcare.framework.exchange.center.core.metadata.IDataApplication;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import xyz.vopen.cartier.classpathscanner.FastClasspathScanner;
import xyz.vopen.cartier.classpathscanner.scanner.ScanResult;

@Slf4j
public class BaseApplicationResolver implements IApplicationResolver {

  @Override
  public void resolve(PluginMetadata metadata) throws Exception {

    ClassLoader classLoader = metadata.getClassLoader();
    FastClasspathScanner fastClasspathScanner = new FastClasspathScanner(
        metadata.getBasePackageName());
    fastClasspathScanner.addClassLoader(classLoader);

    ScanResult result = fastClasspathScanner.scan();
    List<String> apps = result.getNamesOfClassesImplementing(IDataApplication.class);
    metadata.setScanResult(result);

    if (!apps.isEmpty()) {

      //只会初始化一个application
      String appName = apps.get(0);
      IDataApplication appInstance = null;
      try {

        appInstance = (IDataApplication) classLoader.loadClass(appName)
            .newInstance();
      } catch (Exception e) {

        log.error("初始化应用程序异常", e);
      }

      IDataApplication finalAppInstance = appInstance;
      Thread thread = new Thread(() -> finalAppInstance.load(classLoader));
      thread.setContextClassLoader(classLoader);
      thread.run();
      metadata.setApplicationInstance(appInstance);
    }
  }
}
